package com.yang.leather.admin.action;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.octo.captcha.service.image.ImageCaptchaService;
import com.yang.leather.admin.pojo.AdminUser;
import com.yang.leather.admin.service.IAdminUserService;
import com.yang.leather.common.struts2.ContextPvd;

@Scope("prototype")
@Controller("admin.login")
public class LoginAction extends BaseAction{

	private static final long serialVersionUID = 1L;
	
	private String account;
	private String password;
	private String checkCode;
	
	private ImageCaptchaService imageCaptchaService;
	private ContextPvd contextPvd;
	private IAdminUserService adminUserService;
	
	public String toLogin(){
		return SUCCESS;
	}
	
	public String login(){
		boolean isHuman = imageCaptchaService.validateResponseForID(contextPvd.getSessionId(false), checkCode);
		if (!isHuman) {
			addActionError("验证码错误");
			return "loginInput";
		}
		
		AdminUser user = this.adminUserService.authenticate(account, password);
		if (user == null) {
			addActionError("用户不存在");
			return "loginInput";
		}
		
		contextPvd.setSessionAttr(AdminUser.ADMIN_KEY, user);
		return SUCCESS;
	}
	
	public String logout() {
		contextPvd.logout();
		return "logout";
	}

	public String getAccount() {
		return account;
	}

	public void setAccount(String account) {
		this.account = account;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public String getCheckCode() {
		return checkCode;
	}

	public void setCheckCode(String checkCode) {
		this.checkCode = checkCode;
	}

	public ImageCaptchaService getImageCaptchaService() {
		return imageCaptchaService;
	}

	@Autowired
	public void setImageCaptchaService(@Qualifier("imageCaptchaService")
			ImageCaptchaService imageCaptchaService) {
		this.imageCaptchaService = imageCaptchaService;
	}

	public ContextPvd getContextPvd() {
		return contextPvd;
	}

	@Autowired
	public void setContextPvd(@Qualifier("contextPvd")
			ContextPvd contextPvd) {
		this.contextPvd = contextPvd;
	}

	public IAdminUserService getAdminUserService() {
		return adminUserService;
	}
	
	@Autowired
	public void setAdminUserService(@Qualifier("adminUserService")
			IAdminUserService adminUserService) {
		this.adminUserService = adminUserService;
	}
	
}
